import 'package:shared_preferences/shared_preferences.dart';

enum LYMedalType { none, germination, seedlingStage, saplingStage, matureStage }

extension LYMedalTypeValue on LYMedalType {
  int get value {
    switch (this) {
      case LYMedalType.none:
        return -1;
      case LYMedalType.germination:
        return 0;
      case LYMedalType.seedlingStage:
        return 1;
      case LYMedalType.saplingStage:
        return 2;
      case LYMedalType.matureStage:
        return 3;
    }
  }
}

class LYHomeDataManager {
  LYHomeDataManager._internal();
  static final LYHomeDataManager _instance = LYHomeDataManager._internal();
  static LYHomeDataManager get share {
    return _instance;
  }

  int get willUnlockIndex {
    return currentUnlockTree + 1;
  }

  LYMedalType currentUnlockMedal = LYMedalType.none;

  int currentUnlockTree = -1;
  int unlockMedalCount = 0;

  void updateUnlockTreeIndex(int index) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt("unlockTree", index);
    currentUnlockTree = index;
  }

  void updateUnlockType(LYMedalType type) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("medal-${type.index}", true);
    prefs.setInt("unlockType", type.value);
    prefs.setInt("unlockMedalCount", unlockMedalCount);
    currentUnlockMedal = type;
    unlockMedalCount += 1;
  }

  Future<void> initMedal() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final value = prefs.getInt("unlockType") ?? -1;
    currentUnlockTree = prefs.getInt("unlockTree") ?? -1;
    unlockMedalCount = prefs.getInt("unlockMedalCount") ?? 0;
    currentUnlockMedal = initMedalType(value);
  }

  Future<bool> isMedalUnLock(LYMedalType type) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool("medal-${type.index}") ?? false;
  }

  LYMedalType initMedalType(int value) {
    if (value == 0) {
      return LYMedalType.germination;
    } else if (value == 1) {
      return LYMedalType.seedlingStage;
    } else if (value == 1) {
      return LYMedalType.saplingStage;
    } else if (value == 1) {
    } else if (value == 1) {
      return LYMedalType.matureStage;
    }
    return LYMedalType.none;
  }

  Future<void> clearData() async {
    currentUnlockMedal = LYMedalType.none;
    currentUnlockTree = -1;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove("unlockType");
    prefs.remove("unlockTree");
    prefs.remove("unlockMedalCount");
  }
}
